package main

import (
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"mts/user_srv/global"
	"mts/user_srv/internal/repository"
	"mts/user_srv/internal/repository/cache"
	"mts/user_srv/internal/service"
	"mts/user_srv/internal/web"
	"mts/user_srv/ioc"
	customerValidator "mts/user_srv/utils/validator"
)

func failOnError(err error, msg string) {
	if err != nil {
		zap.S().Fatalf("%s: %s", msg, err)
	}
}
func main() {
	ioc.InitLogger()
	ioc.InitConfig()
	db := ioc.InitDB()

	if err := ioc.InitTrans("zh"); err != nil {
		panic(err)
	}
	//注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", customerValidator.ValidateMobile)
		//翻译自定义异常
		_ = v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0} 非法的手机号码", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}
	cmdable := ioc.InitRedis()
	rmq, err := ioc.InitRabbiMQ()
	failOnError(err, "Failed to initialize RabbitMQ")
	defer rmq.Close()
	//repo
	smsService := ioc.InitSMSService()
	codeCache := cache.NewCodeCache(cmdable)
	userRepository := repository.NewUserRepository(db)
	//svc
	userService := service.NewUserService(userRepository, rmq)
	codeService := service.NewCodeService(codeCache, smsService)
	//web
	userHandler := web.NewUserHandler(userService, codeService)
	codeHandler := web.NewCodeHandler(codeService)
	srv := ioc.InitWebServer(userHandler, codeHandler)
	err = srv.Run(":8011")
	if err != nil {
		zap.S().Fatalf("服务启动失败:%s", err.Error())
	}
}
